#
# pH+ 2008
#
# Page class

require 'ph/html/head'
require 'ph/ui/theme'
require 'ph/ui/template'
require 'ph/html/stylesheet'
require 'ph/html/doctype'

module Ph

  class Page < Ph::Container
    
    attr_accessor :doctype
    attr_accessor :header
    attr_accessor :output_file
    attr_reader :application
        
    def initialize(application=$application, pagename=nil)
      super()
      
      @application 	= application
      @tag 					= 'body'
      @doctype 			= Ph::DocType::XHTML1_TRANSITIONAL
      @header 			= Ph::Head.new
			# TODO this is so wrong
			if (pagename)
				@resource_name = pagename
			else
				@resource_name= self.class.name.sub(application.prefix, '').sub('Page', '').downcase if pagename==nil
			end

			@output_file  = @resource_name + '.html'
      
      @theme = Ph::Theme
      @header.body.add Ph::Stylesheet.new(@theme.css)
      
      @properties.delete :id

			self.load_template()
 			self.load_stylesheets()    
      self.setup() if self.respond_to?(:setup)
    end

		def load_template
			template_path = @application.path + '/resources/templates/' + @resource_name + '.html'
			@application.log "Attempting to use #{template_path} as template." if $phDebug

			if File.exists?(template_path) then
				@template = Ph::Template.new(File.new(template_path).read)
			end
		end

		# TODO we could split this up into functions maybe?
		def load_stylesheets

			def load_stylesheet(what)
				@application.log "Attempting to use #{what}." if $phDebug
				css_path = 'resources/css/'
				file     = css_path + what
				@header.body.add(Ph::Stylesheet.new(file)) if File.exists?(file)
			end

			load_stylesheet('default.css')
			load_stylesheet(@resource_name + '.css')

		end
    
    def title= (what)
      @header.title = what 
    end
    
    def title()
      return @header.title
    end
    
    def saveAs(filename)
      file = File.new(filename, 'w')
      file.write(self.to_s)
      file.close
    end
    
    def save()
      #self.saveAs("#{@output_file}")
    end
    
    def to_s
      return "#{@doctype}\n<!-- pH+ Last Generated: #{Time.new} -->\n<html>\n#{@header}\n"  + super + "\n</html>"
    end
  
    def get
	    self.to_s
    end
    
  end
  
end
